package com.ddxz.tool.web.common;

import com.ddxz.tool.core.convert.CollectionUtil;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpRequest;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.util.Map;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/7/22
 */

public class DdxzHttpClient {
    private CloseableHttpClient getHttpClient() {
        return HttpClients.custom().setConnectionManager(pool).setDefaultRequestConfig(requestConfig)
                .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
                .build();
    }

    private String getUrl(String url, Map<String, Object> param) {
        if(CollectionUtil.isEmpty(param)) {
            return url;
        }

        StringBuilder stringBuilder = new StringBuilder(url + "?");
        for(Map.Entry<String, Object> entry : param.entrySet()) {
            stringBuilder.append(String.format("%s=%s&", entry.getKey(), entry.getValue().toString()));
        }

        stringBuilder.deleteCharAt(stringBuilder.length() - 1);

        return stringBuilder.toString();
    }

    private void setHttpHeader(HttpRequestBase requestBase, Map<String, Object> header) {
        if(null == header) {
            return;
        }

        for(Map.Entry<String, Object> entry : header.entrySet()) {
            requestBase.setHeader(entry.getKey(), entry.getValue().toString());
        }
    }

    public DdxzHttpClient() {
        synchronized (pool){
            if(pool == null) {
                try{
                    pool = new PoolingHttpClientConnectionManager();
                    pool.setMaxTotal(20);
                    pool.setDefaultMaxPerRoute(5);
                    requestConfig = RequestConfig.custom()
                            .setConnectionRequestTimeout(6000)
                            .setSocketTimeout(6000)
                            .setConnectTimeout(60000).build();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static PoolingHttpClientConnectionManager pool = null;

    private static RequestConfig requestConfig = null;

    private static final String CHARSET = "UTF-8";
}
